package com.qf.utils;


import cn.hutool.core.util.IdUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


public class ErWeiMaUtil {

    public static String getImgUrl(String content) {
        try {
            int width = 300;
            int height = 300;

            // 生成二维码
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
            BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);

            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    int color = bitMatrix.get(x, y) ? 0x000000 : 0xFFFFFF;
                    image.setRGB(x, y, color);
                }
            }

            // 上传至七牛云
            Configuration cfg = new Configuration();
            UploadManager uploadManager = new UploadManager(cfg);
            Auth auth = Auth.create("eQffyUcuOG7-9cnV7voBiF819D_fnSPS5CssX6MO", "bIQHVEJXYzJNBzTRfDbRFWYOTpthGn_hJlDYLKfj");
            String upToken = auth.uploadToken("xzj2306");
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "png", baos);
            byte[] imageData = baos.toByteArray();
            String key = IdUtil.createSnowflake(0, 0).nextIdStr()+".png";

            Response response = uploadManager.put(imageData, key, upToken);

            // 返回上传后的图片链接
            if (response.isOK()) {
                String imageLink = "http://s32f8klj4.hb-bkt.clouddn.com/" + key; // 替换为您的七牛云存储主机地址
                return imageLink;
            } else {
                return "Image upload failed";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "Error generating and uploading QR code.";
        }
    }
}
